// import PromptManage from "../../Game/PromptManage";
// import UserData from '../../Game/UserData';
// import SocketHelper from "../../Game/SocketHelper";
import GameUtil from './GameUtil';
import PromptManage from '../../Game/PromptManage';

export default class JsbUtil {

    public static isAndroid = cc.sys.platform == cc.sys.ANDROID;
    public static androidSwitch = false;
    public static androidJavaPath = "org.cocos2dx.javascript.CocosHelp";
    public static wxLoginCallback = null;
    public static huaweiLoginCallback = null;
    public static downloadCallback = null;
    public static callback = null;
    public static targrt = null;
    public static interceptorCallback = null;
    public static interceptor2Callback = null;
    public static createPDFCallback = null; //回调
    public static locationCallback = null;
    public static videoSwicth = false;
    public static videoCallback = null; 
    public static videoCallfun = null;

    //-------------------------------------cc的回调 现在改到JsbUtil里了------------------------------
    public static onBackPressed = function () {
        this.backFunction();
    };
    public static extendBack = null;
    static awakenAdCallback: (str: any) => void;
    static adCallback: any;
    
    
    public static init() {
        var self = this;
        if (!JsbUtil.onBackPressed) {
            JsbUtil.onBackPressed = function () {
                self.backFunction();
            };
        }
    }
    public static initAndroidCallback(){
        //如果视频开关打开则弹窗
        if(this.checkCanVideo() == true){
            PromptManage.addDialog('观看完整视频可获得随机卡片一张',1);
        }
    }
    public static showVideoCallback(success){
        if(success == true && this.videoCallfun){
            this.videoCallfun();
        }else{
            Log('未能获取到奖励')
            
            
        }
    }
    // public static getVideoCallback(){
    //     return this.videoCallback;
    // }
    public static checkCanVideo(){
        let videoSwicth = jsb.reflection.callStaticMethod(this.androidJavaPath, "checkCanVideo", "()Z");
        return videoSwicth;
    }
    public static showVideo(videoCallfun){
        if (this.isAndroid) {
            Log('展示视频广告');
            jsb.reflection.callStaticMethod(this.androidJavaPath, "showVideo", "()V");
            this.videoCallfun = videoCallfun;
        }
    }
    public static showCp(){
        if (this.isAndroid) {
            Log('展示插屏广告');
            jsb.reflection.callStaticMethod(this.androidJavaPath, "showCp", "()V");
        }
    }
    public static yszc(){
        Log("打开安卓隐私政策窗口")
        if(this.isAndroid){
            jsb.reflection.callStaticMethod(this.androidJavaPath, "showYszc", "()V");
        }
    }

    public static wxLogin() {
        if (this.isAndroid) {
            Log('申请微信登录')
            JsbUtil.wxLoginCallback = (wxInfo) => {
                // 微信登录成功回调此方法，并返回wxInfo，失败不回调
                // wxInfo 内容格式说明
                // {
                //     "openid":"oJ6_jvp9dtM0kGYsux6jtkANBA3Q",
                //     "nickname":"淡然处之",
                //     "sex":2,"language":"zh_CN","city":"Jiaozuo","province":"Henan","country":"CN",
                //     "headimgurl":"http:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/yxHqAIqgfibHVg6VCSlNRL9LWUEQfoLSUDmicHPCxdFqgvJp2zFaFlrAmMdPVuuhWlM6fx21znt1q6AMB17g09CQ\/132",
                //     "privilege":[],
                //     "unionid":"oXiX7siJgj7KsH8kyDC_yxTU5z1g"
                // }
                // if(!wxInfo){
                //     Log('微信登录有问题,弹出登录失败,',JSON.stringify(wxInfo));
                //     PromptManage.addToast('登录失败,请重新登录!')
                //     return;
                // }
                // else{
                //     UserData.wxid = wxInfo.openid;
                //     SaveLocal('wxid', UserData.wxid);
                //     SaveLocal('unionid', wxInfo.unionid);
                //     UserData.headImgUrl = wxInfo.headimgurl;
    
                //     SaveLocal('headUrl', wxInfo.headimgurl);
                //     SaveLocal('usNickName', wxInfo.nickname);
                //     SaveLocal('usSex', wxInfo.sex);
                //     Log('微信登录刷新个人信息 = ', JSON.stringify(wxInfo));
                //     UserData.nickName = wxInfo.nickname;
                //     UserData.sex = wxInfo.sex == 2 ? '女' : '男';
                //     let callback = (succ)=>{
                //         if (succ){
                //             GameUtil.gotoScene('MainScene');
                //         }
                //         else{
                //             PromptManage.addToast('连接服务器失败,请重新启动APP!',()=>{cc.game.end()});
                //         }
                //     }
                //     SocketHelper.Login(callback, 2,UserData.nickName,UserData.sex,UserData.headImgUrl);
                // }
            }

            jsb.reflection.callStaticMethod(this.androidJavaPath, "wxLogin", "()V");
        }
    }

    // public static huaweiLogin(back) {
    //     if (this.isAndroid) {
    //         Log('申请华为登录')
    //         this.huaweiLoginCallback = back;
    //         cc.huaweiLoginBack = (success) => {
    //             Log("huaweiLogin", "华为登录--服务器登录回调");
    //             SocketHelper.updateUserInfo();
    //             if (JsbUtil.huaweiLoginCallback) {
    //                 JsbUtil.huaweiLoginCallback(success);
    //             }
    //             else {
    //                 Log("huaweiLoginCallback", '没有找到回调函数')
    //             }

    //         }
    //         cc.huaweiLoginCallback = (huaweiInfo) => {
    //             Log("huaweiLoginCallback --> ", huaweiInfo)
    //             Log("huaweiInfo.hwId --> ", huaweiInfo.hwId);

    //             // let huaweiInfo1 = JSON.stringify(huaweiInfo);
    //             // Log("huaweiLoginCallback jsonString --> ", huaweiInfo1)
    //             // Log("huaweiInfo1.hwId --> ", huaweiInfo1.hwId);

    //             UserData.hwid = huaweiInfo.hwId;
    //             SaveLocal('hwid', huaweiInfo.hwId);

    //             UserData.headImgUrl = huaweiInfo.headUrl;
    //             SaveLocal('headUrl', huaweiInfo.headUrl);

    //             UserData.nickName = huaweiInfo.nickName;

    //             SocketHelper.Login(cc.huaweiLoginBack, 1);
    //         }

    //         jsb.reflection.callStaticMethod(this.androidJavaPath, "huaweiLogin", "()V");
    //     }
    // }
    private static upFilesCallback;
    public static upFiles(fileName,filePath){
        let self = this;
        if (!this.isAndroid){
            return null;
        }
        return new Promise((resolve,reject)=>{
            Log("上传图片 --》 ", fileName , "  --  ", filePath);
            jsb.reflection.callStaticMethod(
                this.androidJavaPath,
                "upFiles",
                "(Ljava/lang/String;Ljava/lang/String;)V", fileName,filePath);

            self.upFilesCallback = (success, httpPath)=>{
                if (success){
                    resolve(httpPath);
                }
                else{
                    reject(null);
                }
            }
        })
    }


    public static checkInstall(packname) {
        if (this.isAndroid) {
            return jsb.reflection.callStaticMethod(this.androidJavaPath,
                "checkInstall",
                "(Ljava/lang/String;)Z", packname);
        }
        else {
            return false;
        }
    }
    public static wxShare() {
        Log('微信分享参数:',UserData.wxShareUrl, UserData.wxShareTitle, UserData.wxShareContent, UserData.wxShareImg)
        if (this.isAndroid) {
            Log('申请微信分享');
            // var wxShareUrl = "";
            // var wxShareTitle = "";
            // var wxShareContent = "";
            // var wxShareImg = "";
            jsb.reflection.callStaticMethod(this.androidJavaPath,
                "wxShare",
                "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
                UserData.wxShareUrl, UserData.wxShareTitle, UserData.wxShareContent, UserData.wxShareImg);
        }
    }

    public static appStar() {
        if (this.isAndroid) {
            Log('申请评分');
            jsb.reflection.callStaticMethod(this.androidJavaPath,
                "appStar3",
                "()V");
        }
    }

    public static getAndroidAdName() {
        if (this.isAndroid) {
            // Log('传参拉传参啦 str = ',str)
            return jsb.reflection.callStaticMethod(this.androidJavaPath, "getAndroidAdType", "()Ljava/lang/String;");
        }
    }
    /**
     * 将广告配置信息传给Android做初始化
     * @param str
     */
    public static setAndroidAdJson(str) {
        if (this.isAndroid) {
            Log('传参拉传参啦 str = ', str)
            jsb.reflection.callStaticMethod(this.androidJavaPath, "initAdConfig", "(Ljava/lang/String;)V", str);
        }
    }
    public static setAndroidWakeJson(str) {
        if (this.isAndroid) {
            // Log('传参拉传参啦 str = ',str)
            jsb.reflection.callStaticMethod(this.androidJavaPath, "initAwakenAd", "(Ljava/lang/String;)V", str);
        }
    }

    public static awakenAd(back) {
        if (this.isAndroid) {
            // Log('传参拉传参啦 str = ',str)
            jsb.reflection.callStaticMethod(this.androidJavaPath, "awakenAd", "()V");
            JsbUtil.awakenAdCallback = function (str) {
                back && back(str);
            }
        }
        else {
            back && back('true');
        }

    }
    /**
     * 统计
     * @param {*} id 统计类型 
     * soucong 首冲，danpin 单品，taozhuang 套装，qiandao 签到，daoju 道具，tiaozhan 挑战
     * @param {*} propId 统计说明
     * 例如首冲：点击首冲，首冲成功，中止首冲
     * 例如单品：点击购买（baobao1），购买成功（baobao1），中止购买（baobao1）
     * 例如视频单品：成功购买视频单品（yifu1）
     * 例如套装：点击购买（tz1），购买成功（tz1），中止购买（tz1）
     * 例如道具：点击购买（quan10），购买成功（quan10），中止购买（quan10）
     * 例如挑战：挑战成功（1-1），挑战失败（1-1）
     * @param {*} pos 如果pos等于012，则msg代表道具名
     */
    public static sendTj(lockStatus, propId, pos = -1) {
        var msg = propId;
        if (pos == 0) {
            msg = "点击购买(" + propId + ")";
        }
        if (pos == 1) {
            msg = "购买成功(" + propId + ")";
        }
        if (pos == 2) {
            msg = "中止购买(" + propId + ")";
        }
        var id = lockStatus;
        switch (lockStatus) {
            case 1:
                id = "tiaozhan";
                break
            case 2:
                id = "taozhuang";
                break
            case 3:
                id = "danpin";
                break
            case 4:
                id = "qiandao";
                break
            case 5:
                id = "soucong";
                break
            case 6:
                id = "danpin";
                msg = "成功购买视频单品(" + propId + ")";
                break
            case 7:
                id = "dianji";
                break
        }
        Log("开始统计 id=" + id, " msg=", msg);
        if (this.isAndroid) {
            jsb.reflection.callStaticMethod(this.androidJavaPath, "sendTj", "(Ljava/lang/String;Ljava/lang/String;)V", id, msg);
        }
    }

    public static onRestart(time){
        console.log("JsbUtils onRestart")
    }

    public static setOnRestart(callback) {
        JsbUtil.onRestart = callback;
        if (!JsbUtil.onRestart) {
            JsbUtil.onRestart = function (key) {
                if (JsbUtil.onRestart) {
                    Log("onRestart 存在，开始回调")
                    JsbUtil.onRestart(key);
                } else {
                    Log("onRestart 不存在，中止回调")
                }
            };
        }
    }

    public static download(str, callback) {
        if (this.isAndroid) {
            var info = JSON.stringify(str);
            Log('下载文件 info = ', info);
            if (callback) {
                this.downloadCallback = callback;
            }
            jsb.reflection.callStaticMethod(this.androidJavaPath, "download", "(Ljava/lang/String;)V", info);
            var self = this;
            JsbUtil.downloadCallback = function (porgress) {
                if (self.downloadCallback) {
                    self.downloadCallback(porgress);
                } else {
                    Log("下载回调不存在：" + porgress);
                }
            }
        }
    }

    public static savePictureToLocal(path) {
        if (this.isAndroid)
            jsb.reflection.callStaticMethod(this.androidJavaPath, "savePictureToLocal", "(Ljava/lang/String;)V", path);
    }

    public static saveWallpaper(path) {
        if (this.isAndroid)
            jsb.reflection.callStaticMethod(this.androidJavaPath, "saveWallpaper", "(Ljava/lang/String;)V", path);
    }

    public static showAndroidToast(msg) {
        if (this.isAndroid)
            jsb.reflection.callStaticMethod(this.androidJavaPath, "toast", "(Ljava/lang/String;)V", msg);
    }

    /**
     * 设置Android端广告播放解锁回调
     * success true:false
     */
    public static setAndroidAdListence(callback) {
        JsbUtil.adCallback = callback;
        JsbUtil.adCallback = function (success) {
            Log("Cocos 广告解锁回调 ", success);
            if (success) {
                JsbUtil.adCallback && JsbUtil.adCallback();
            }
        }
        if (cc.sys.platform == cc.sys.MOBILE_BROWSER) {
            JsbUtil.adCallback(true);
        }
    }

    public static showAndroidAd(callback) {
        Log("Cocos 道具购买 广告 ");
        if (this.isAndroid) {
            this.setAndroidAdListence(callback);
            jsb.reflection.callStaticMethod(this.androidJavaPath, "showVideoAd", "()V");
        }
        // if(callback){
        //     callback();
        // }

    }

    //{"propName": "手链0","id":"mry-shoulian0", "payGold": 100, "payAd": 4, "payRmb": 1.5, "payType":"gold", "belongLevel":0...},
    public static showAndroidRmbPay(propInfo) {
        Log("Cocos 道具购买 RMB ", propInfo);
        if (this.isAndroid) {
            jsb.reflection.callStaticMethod(this.androidJavaPath, "buyRmbProp", "(Ljava/lang/String;F)V", propInfo.id, propInfo.payRmb);
        }
    }

    public static getAndoridInfoUrl() {
        // return "true";
        if (this.isAndroid) {
            var url = jsb.reflection.callStaticMethod(this.androidJavaPath, "getAndoridInfoUrl", "()Ljava/lang/String;");
            Log("获取配置地址:", url);
            return url;
        } else {
            return false;
        }
    }

    /**
     * 1漫画屋，2灵感屋，3游乐场，4故事屋，5闯关，6美甲，7换装，8礼包
     * 11反馈，12签到，13任务，14抽奖，15商城，16ad1, 17ad2
     * @param {*} position 
     */
    public static openAndroid(position) {
        Log("Cocos 打开Andorid功能 = " + position);
        if (this.isAndroid) {
            jsb.reflection.callStaticMethod(this.androidJavaPath, "sceneChange", "(I)V", position);
        }
    }




    public static showVideoAd() {
        Log("Cocos 播放视频广告");
        // if (this.isAndrid && UserData.mainSwitch) {
        if (this.isAndroid) {
            jsb.reflection.callStaticMethod(this.androidJavaPath, "showVideoAd", "()V");
        }
    }

    // showChapinAd(){
    //     Log("Cocos 播放插屏广告");
    //     if (this.isAndrid && UserData.mainSwitch) {
    //         jsb.reflection.callStaticMethod(this.androidJavaPath, "showChapinAd", "()V");
    //     }
    // },

    public static listenAndroidBack() {
        // cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP);
        // cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, function (event) {
           
        // });
        this.setAndroidBackListence(function(){
            Log("当前场景的名字1---------》",GameUtil.sceneName);
            if(GameUtil.sceneName != "MainScene"){
                GameUtil.gotoScene("MainScene");
                Log("当前场景的名字2---------》",GameUtil.sceneName);
            }else{
                Log("当前场景的名字3---------》",GameUtil.sceneName);
                if(cc.find("Canvas/Exit") == null){
                    PromptManage.addExitDialog(true);
                }
            }
        })
    }

    /**
     * 设置闹钟
     * @param hour 
     * @param minute 
     */
    static startAlarm(hour: number, minute: number) {
        if (this.isAndroid) {
            jsb.reflection.callStaticMethod(this.androidJavaPath, "startAlarm", "(II)V", hour, minute);
        } else {
            Log("非Andorid环境")
        }
    }

    /**
     * 关闭闹钟
     */
    static stopAlarm() {
        if (this.isAndroid) {
            jsb.reflection.callStaticMethod(this.androidJavaPath, "stopAlarm", "()V");
        } else {
            Log("非Andorid环境")
        }
    }
    /********************************图片选择*********************************************/
    /**
     * 设置图片选择回调方法
     * @param callback (ImgPath, SpriteFrame)
     */
    static setSelectImgCallback(callback: Function) {
        this.mSelectImgCallback = callback;
    }

    private static mSelectImgCallback;
    /**
     * 用于 Android 端调用
     * @param path 图片地址
     */
    static selectImgCallback(path: string) {
        Log("图片选择地址回调：", path);
        // if (path) {
        //     cc.loader.loadRes(path, cc.SpriteFrame, function (error, res) {
        //         JsbUtil.mSelectImgCallback && JsbUtil.mSelectImgCallback(path, res);
        //     })
        // } else {
            JsbUtil.mSelectImgCallback && JsbUtil.mSelectImgCallback(path);
        // }

    }

    /**
     * 选择本地图片
     */
    static selectImg() {
        if (this.isAndroid) {
            jsb.reflection.callStaticMethod(this.androidJavaPath, "openImgSelect", "()V");
        } else {
            Log("非Andorid环境")
        }
    }
    static createPDF(str,callback){
        Log('传递的字符串 = ',str)

        this.createPDFCallback = callback;
        if (this.isAndroid) {
            jsb.reflection.callStaticMethod(this.androidJavaPath, "createPDF", "(Ljava/lang/String;)V",str);
        } else {
            Log("非Andorid环境")
        } 
    }
    static startLocation(callback){
        this.locationCallback = callback;
        if (this.isAndroid) {
            jsb.reflection.callStaticMethod(this.androidJavaPath, "startLocation", "()V");
        } else {
            Log("非Andorid环境")
        } 
    }
    static setAlias(){
        if (this.isAndroid) {
            jsb.reflection.callStaticMethod(this.androidJavaPath, "setAlias", "(Ljava/lang/String;)V",UserData.usid);
        } else {
            Log("非Andorid环境")
        } 
    }

    static showLoading(show: boolean) {
        if (this.isAndroid) {
            jsb.reflection.callStaticMethod(this.androidJavaPath, "showLoading", "(Z)V", show);
        } else {
            Log("非Andorid环境")
        }
    }

    /************************************************** 打包Android 必备 ************************************************************* */
    
    /**
     * 每个场景中调用setAndroidBackListence() 监听Android端返回按钮
     * 
     * 需要Android端CocosHelp配合，CocosHelp中必须存在goBack()方法，goBack返回true则表示Android端拦截了本次事件，一般默认返回false
     * 本方法适配了特殊机型导致的cc监听不到的情况，需要在AppActivity中的onBackPressed（）方法下回调ackFunction()
     * 如下：
        @Override
        public void onBackPressed() {
            SDKWrapper.getInstance().onBackPressed();
            Log.i("CocosHelp", "点击返回按钮");
            CocosHelp.onBackPressed();
            // super.onBackPressed();
        }

        *** CocosHelp必备方法：

        public class CocosHelp {

            public static void onBackPressed(){
                Cocos2dxHelper.runOnGLThread(new Runnable() {
                @Override
                public void run() {
                    Cocos2dxJavascriptJavaBridge.evalString("JsbUtil.backFunction()");
                }
                });
            }

            public static boolean goBack(){
                return false;
            }

        }

     * 
     * @param callback Android原生不拦截则回调（如无特殊情况，可在此执行退出弹窗）
     * @param targrt 
     * @param interceptorCallback 本地拦截器 返回true则为拦截后续操作
     */
    public static setAndroidBackListence(callback, targrt?, interceptorCallback?){
        this.callback = callback;
        this.targrt = targrt;
        this.interceptorCallback = interceptorCallback;
        var self = this;
        console.log("注册了返回按钮");
        cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP);
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, function(event){
            console.log("用户点击了返回按钮", event.keyCode + " : " + cc.macro.KEY.back);
            // 8 键盘的回退键
            if(event.keyCode == cc.macro.KEY.back || event.keyCode == 8){
                self.backFunction();
            }
        },targrt);
    }

    public static setInterceptor2Callback(interceptor2Callback){
        this.interceptor2Callback = interceptor2Callback;
    }

    public static backFunction() {
        if (this.interceptor2Callback) {
            var interceptor = this.interceptor2Callback();
            if (interceptor && interceptor == true) {
                Log("Cocos 二级拦截器 拦截了返回事件");
                return;
            }
        }

        if (this.interceptorCallback) {
            var cancel = this.interceptorCallback();
            if (cancel && cancel == true) {
                Log("Cocos拦截了返回事件");
                return;
            }
        }

        if (this.isAndroid) {
            var result = jsb.reflection.callStaticMethod(this.androidJavaPath, "goBack", "()Z");
        }

        if (result && result == true) {
            Log("Andorid拦截了返回事件");
        } else if (this.callback) {
            this.callback();
        }
    }
}
window["JsbUtil"] = JsbUtil;